package com.red.service.impl;

import com.red.entity.House;
import com.red.mapper.HouseMapper;
import com.red.service.HouseService;

import java.util.List;

public class HouseServiceImpl extends Service implements HouseService {
    private HouseMapper mapper;

    public HouseServiceImpl() {
        mapper = session.getMapper(HouseMapper.class);
    }

    public House[] getRandomHouses(int size) {
        int count = mapper.selectSize(new String[]{"未出租"});
        int pages = (int) (Math.floor(count / (double) size));
        int offset = (int) (Math.random() * (pages - 1) + 1);
        House[] houses = mapper.selectHouses(size, offset, new String[]{"未出租"});
        destroy();
        return houses;
    }

    public House[] getHouses(int size, int page) {
        return getHouses(size, page, new String[]{"未出租","洽谈中"});
    }

    public House[] getHouses(int size, int page, String[] status) {
        int offset = (page - 1) * size;
        House[] houses = mapper.selectHouses(size, offset, status);
        destroy();
        return houses;
    }

    public House getHouse(int house_id){
        House house = mapper.selectByID(house_id);
        destroy();
        return house;
    }

    public int getSize(String[] status) {
        int size = mapper.selectSize(status);
        destroy();
        return size;
    }

    public boolean addHouse(House house) {
        boolean result;

        if (mapper.insertHouse(house.getHouse_name(), house.getPrice(), house.getAddress(), house.getDetailed_address(), house.getDescription()) > 0) {
            result = true;
        } else {
            result = false;
        }
        destroy();
        return result;
    }

    public int deleteHouse(List<Integer> ids) {
        int result;

        result = mapper.deleteHouses(ids);
        destroy();
        return result;
    }

    public boolean updateHouse(House house) {
        int count;

        if (house.getHouse_id() != null) {
            count = mapper.updateHouse(house);
            destroy();
        } else
            return false;
        return count > 0;
    }
}
